import {Text, View} from "@tarojs/components";
import React, {useCallback, useEffect, useRef, useState} from "react";

import {OrderItem, KeyTitleModel, RelationModel} from "@/common/apis/model";
import {orderTeamApproveApi, teamApproveListApi, teamViewListApi} from "@/common/apis/home_datasource";
import LogUtils from "@/utils/log";
import Utils from "@/utils/common";
import {Button, Cell, Divider, Empty, Image, Tab, Tabs} from "@antmjs/vantui";
import {usePullDownRefresh} from "@tarojs/taro";
import {getOrderStatusStyle} from "@/common/enums";
import RouthPath from "@/common/RouthPath";
import ShowUtils from "@/utils/show_utils";
import LocalData from "@/common/local_data";
import NumberUtils from "@/utils/number_utils";


definePageConfig({
  enablePullDownRefresh: true,
  navigationBarTitleText: '课题组项目'
})

export default function Research_team_project() {

  const [tabs, setTabs] = useState<KeyTitleModel[]>([])

  const relationModel = useRef<RelationModel>();
  //
  useEffect(() => {
    const params = Utils.getParamsByRouter(Utils.getI())
    if (params && params.data) {
      relationModel.current = Utils.getObjectWithUrl<RelationModel>(params.data)
      const tabList = []
      if (relationModel.current) {
        if (relationModel.current.viewPower === 1) {
          tabList.push(
            {
              title: '全部',
              key: 0 // Key is the actual enum value (10)
            }
          )
        }
        if (relationModel.current.approve === 1) {
          tabList.push(
            {
              title: '待审核',
              key: 2 // Key is the actual enum value (10)
            }
          )
        }
      }
      tabList.push({
        title: '我的',
        key: 1 // Key is the actual enum value (10)
      })
      setTabs(tabList)
    }
  }, []);


  return (
    <View>
      {
        Utils.isEmpty(tabs) ? <Empty description='暂无数据'/> : tabs.length == 1 ?
          <ResearchItemProjectList type={1} teamId={relationModel.current.teamId}></ResearchItemProjectList> : <Tabs
            sticky
            color='#56abe4'
          >
            {
              tabs.map((item, index) => (
                <Tab key={`tabs#demo1${index}`} title={item.title}>
                  <View>
                    <ResearchItemProjectList type={item.key}
                                             teamId={relationModel.current.teamId}></ResearchItemProjectList>
                  </View>
                </Tab>
              ))
            }
          </Tabs>
      }
    </View>
  )
}


function ResearchItemProjectList(pros) {
  const [items, setItems] = useState<OrderItem[]>()

  const getList = useCallback((isRefresh = false) => {
    const api = pros.type !== 2 ? teamViewListApi(pros.teamId, pros.type, isRefresh) : teamApproveListApi(pros.teamId, isRefresh);
    api.then((res) => {
      if (res) {
        setItems(res)
      }
    })
  }, [pros.teamId, pros.type]);

  usePullDownRefresh(() => {
    getList(true)
  })

  useEffect(() => {
    getList()
    return () => {
      LogUtils.info("ResearchItemProjectList", "ResearchItemProjectList")
    }
  }, [getList]);

  const handleButtons = useCallback((e, item, type) => {
    e.stopPropagation(); // 阻止事件冒泡到父级的 onClick
    Utils.modal('提示', `确定${type === 1 ? '通过' : '拒绝'}吗？`, true, (ok) => {
      if (ok) {
        orderTeamApproveApi(pros.teamId, item.id, type).then((res) => {
          if (res) {
            getList()
          }
        })
      }
    })
  }, []);

  const renderActionButtons = useCallback((item) => {
    let buttons = null;
    // 使用枚举值会更清晰和安全
    if (pros.type === 2) { // 状态为 2
      buttons = (
        <View>
          <Button size='normal' type='info' onClick={(e) => {
            handleButtons(e, item, 1);
          }}
          >
            通过
          </Button>
          <Button style={{marginLeft: '10px'}} size='normal' type='danger' hairline plain onClick={(e) => {
            handleButtons(e, item, 2);
          }}
          >
            拒绝
          </Button>
        </View>
      );
    }
    if (buttons) {
      return (
        <View>
          <View style={{
            display: 'flex',
            flexDirection: 'row',
            paddingRight: '20px',
            paddingBottom: '10px', // 给按钮下方留出一些空间
            boxSizing: 'border-box',
            justifyContent: 'flex-end',
          }}
          >
            {buttons}
          </View>
          <Divider style={{marginTop: '0px'}}/> {/* 如果按钮存在，Divider 可以在按钮之后 */}
        </View>
      );
    }
    return null; // 如果没有匹配的状态，则不渲染按钮区域
  }, [handleButtons, pros.type]);

  const showTimeOrNum = useCallback((item: OrderItem) => {
    const type = item.machineType
    if (type === LocalData.notTimeId) {
      return `样品数量：${NumberUtils.stringToNumber(item.bookTotalTime)}`
    } else {
      return `预约时间：${ShowUtils.getShowTime(item.bookAllTimes)}`
    }
  }, []);
  return (
    <View style={{backgroundColor: 'white'}}>
      {
        items && !Utils.isEmpty(items) ? <View>
          {
            items.map((item, index) => {
              const orderStatusInfo = getOrderStatusStyle(item.status)
              return <View key={index} onClick={() => {
                const url = Utils.getUrlWithObject(RouthPath.orderDetail, {
                  id: item.id,
                  isHideButton: true,
                })
                Utils.navigateTo({
                  url: url
                })
              }}
              >
                <Cell renderIcon={<Text style={{fontSize: '14px'}}>订单号：{item.id}</Text>}
                      renderTitle={<Text
                        style={{
                          color: orderStatusInfo.color,
                          textAlign: 'right',
                          fontSize: '14px',
                          width: '100%',
                          display: 'inline-block',
                        }}
                      >{orderStatusInfo.text}</Text>}

                />
                <View style={{display: 'flex', flexDirection: 'row', padding: '10px 20px', boxSizing: 'border-box'}}>
                  <View>
                    <Image src={item.projectImage} style={{width: '150px', height: '150px'}} mode='aspectFill'/>
                  </View>
                  <View
                    style={{marginLeft: '10px', display: 'flex', flexDirection: 'column', flex: 1, height: '150px'}}
                  >
                    <Text>机器：{item.machineName}</Text>
                    <View>
                      <Text>项目：{item.projectName}</Text>
                      {/*{item.note ? <Text style={{color: 'gray',fontSize: '12px'}}>{`(${item.note})`}</Text> : null}*/}
                    </View>
                    <Text>{showTimeOrNum(item)}</Text>
                    <View style={{flex: 1, display: 'flex', justifyContent: 'flex-end'}}>
                      <Text style={{
                        fontSize: '16px',
                        color: 'red',
                        textAlign: 'right',
                        marginTop: '10px',
                        alignSelf: 'flex-end'
                      }}
                      >{ShowUtils.getDefaultPrice(item.actualAmount)}</Text>
                      <Text style={{
                        fontSize: '16px',
                        color: 'gray',
                        textAlign: 'right',
                        marginTop: '10px',
                        alignSelf: 'flex-end',
                        textDecoration: 'line-through',
                      }}
                      >{`(${ShowUtils.getDefaultPrice(item.amount)})`}</Text>
                    </View>
                  </View>
                </View>
                <Divider style={{margin: '10px 20px'}}/>
                {
                  renderActionButtons(item)
                }
              </View>
            })
          }
        </View> : <Empty description='暂无数据'/>
      }
    </View>
  )
}


